package ch.janotta.slawo.utilities;

import java.util.Arrays;

public final class ArrayTools {
  // Don't allow to instantiate this utility class
  private ArrayTools() {};

  public static <T> T[] randomizeArray(T[] in) {
    int n = in.length;
    T[] out = Arrays.copyOf(in, n);
    for (int i = 0; i < n; i++) {
      int index1 = Dice.getRandomNumber(n) - 1;
      int index2 = Dice.getRandomNumber(n) - 1;
      T value1 = out[index1];
      T value2 = out[index2];
      out[index1] = value2;
      out[index2] = value1;
    }
    return out;
  }

  public static int[] randomizeArray(int[] in) {
    return asInt(randomizeArray(asInteger(in)));
  }

  private static Integer[] asInteger(int[] in) {
    Integer[] out = new Integer[in.length];
    for (int i = 0; i < in.length; i++) {
      out[i] = in[i];
    }
    return out;
  }

  private static int[] asInt(Integer[] in) {
    int[] out = new int[in.length];
    for (int i = 0; i < in.length; i++) {
      out[i] = in[i];
    }
    return out;
  }

  public static int[] randomizeIntArray(int[] in) {
    int n = in.length;
    int[] out = Arrays.copyOf(in, n);
    for (int i = 0; i < n; i++) {
      int index1 = Dice.getRandomNumber(n) - 1;
      int index2 = Dice.getRandomNumber(n) - 1;
      int value1 = out[index1];
      int value2 = out[index2];
      out[index1] = value2;
      out[index2] = value1;
    }
    return out;
  }

  public static <T> T getRandomMember(T[] a) {
    int numberOfMembers = a.length;
    int randomIndex = Dice.getRandomNumber(numberOfMembers) - 1;
    return a[randomIndex];
  }

  public static <T> T[] getRandomMembers(T[] a, int numberToSelect) {
    int numberOfMembers = a.length;
    if (numberToSelect > numberOfMembers) {
      numberToSelect = numberOfMembers;
    }
    T[] randomizedArray = randomizeArray(a);
    return Arrays.copyOf(randomizedArray, numberToSelect);
  }

  public static int[] getRandomIndices(int numberOfIndices) {
    int[] indices = new int[numberOfIndices];
    for (int i = 0; i < numberOfIndices; i++) {
      indices[i] = i;
    }
    return randomizeIntArray(indices);
  }
}
